package com.digital.herbarium.Util;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.digital.herbarium.Exception.CustomException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class ExcelUtilHandler {


    public static  ExcelReader getExcelReader(MultipartFile file, HttpServletRequest request, String uploadPath) {
        if (file.isEmpty()) {
            System.out.println("文件为空");
            throw new CustomException(400, "文件为空");

        }

        //文件名
        String fileName = file.getOriginalFilename();
        //后缀名
        File file1 = new File(uploadPath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        ExcelReader reader = null;
        if (fileName != null && !"".equals(fileName.trim())) {

            //创建文件
            File desFile = new File(uploadPath + File.separator + fileName);
            //将源文件写入服务器
            try {
                file.transferTo(desFile);
            } catch (IOException e) {
                e.printStackTrace();
            }

            reader = ExcelUtil.getReader(desFile);
        }
        return reader;
    }

}
